package com.xiaozeng.user.shiro;

import lombok.val;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.spring.web.config.DefaultShiroFilterChainDefinition;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @Author: xiaozeng
 * @Date: 2022 11
 * @Description:
 **/
@Configuration
public class ShiroConfig {
    //告诉Shiro我们自定义了MyRealm对象
    @Autowired
    private MyRealm myRealm;


    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(DefaultWebSecurityManager defaultWebSecurityManager){
        ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
        //设置安全管理器，也可以用作拦截器
        bean.setSecurityManager(defaultWebSecurityManager);
        /*
        过滤器参数
        anon:无需认证就可以访问
        authc:必须认证了才能让问
        user:必须棚有记住我功能才能用
        perms:拥有对某个资源的权限才能访问：
        role:拥有某个角色权限才能访问
        */
        //拦截
        Map<String,String> filterMap = new LinkedHashMap<>();
        //权限
        filterMap.put("/user/login","anon");
        filterMap.put("/collect/**","authc");//收藏功能需要登录
        filterMap.put("/order/**","authc");//下单功能需要登录
        filterMap.put("/cart/**","authc");//购物车功能需要登录
        bean.setFilterChainDefinitionMap(filterMap);
        //设置不满足权限时跳转的请求
        bean.setLoginUrl("/user/Unauthorized");
        bean.setUnauthorizedUrl("/user/Unauthorized");
        return bean;
    }


    //DefaultWebSecurityManager
    @Bean
    public DefaultWebSecurityManager getDefaultWebSecurityManager() {
        //1创建defaultWebSecurityManager对象
        DefaultWebSecurityManager manager = new DefaultWebSecurityManager();
        //2创建加密对象，设置相关属性
        HashedCredentialsMatcher matcher = new HashedCredentialsMatcher();
        //2.1采用md5加密
        matcher.setHashAlgorithmName("md5");
        //2.2加密次数
        matcher.setHashIterations(3);
        //matcher.setHashSalted();已经弃用，在MyRealm中设置
        //3将加密对象存储到myReaLm中
        myRealm.setCredentialsMatcher(matcher);
        //4将myReaLm存入defaultWebSecurityManager对象
        manager.setRealm(myRealm);
        //5返回
        return manager;
    }
}
